import React, {useState} from 'react';
import ProForm, {ProFormText, ProFormTextArea, ProFormUploadButton} from '@ant-design/pro-form';
import {Modal, message, TreeSelect, Form} from 'antd';
import {addApi, editApi} from '@/services/setting';


const Edit = (props) => {
  const {isModalVisible, isShowModal, actionRef, editData, cateData} = props;

  const [formLayout] = useState('horizontal');

  const title = editData === null ? '添加用户' : '编辑用户';

  const formItemLayout =
    formLayout === 'horizontal'
      ? {
        labelCol: {span: 4},
        wrapperCol: {span: 20},
      }
      : null;

  /**
   * 提交按钮
   * @param values
   * @returns {Promise<void>}
   */
  const handleSubmit = async values => {
    const data = values
    let res = {}
    if (editData === null){
      res = await addApi(data)
    }else {
      data.api_id = editData.api_id
      res = await editApi(data)
    }

    if(res.code === 200){
      message.success(res.msg)
      actionRef.current.reload()
      isShowModal(false)
    }
  }

  const handleCateData = data => {
    data.api_pid = data.api_pid === 0 ? null: data.api_pid;
    return data;
  }

  // 递归修改data属性值，配合treeSelect规范数据
  const handleData = data => {
    let item = [];
    data.map((list, i) => {
      let newData = {};
      newData.value = list.api_id;
      newData.title = list.api_name;
      newData.children = list.children ? handleData(list.children) : []; // 如果还有子集，就再次调用自己
      item.push(newData);
    });
    return item;
  };

  // const onChange = value => {
  //   console.log(value);
  // };

  // const

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <ProForm
        onFinish={values => handleSubmit(values)}
        initialValues={editData === null ? {
          api_sort: 200
        } : handleCateData(editData)}
        {...formItemLayout}
        layout={formLayout}
      >
        <Form.Item
          label="接口父级"
          name="api_pid"
        >
          <TreeSelect
            style={{width: '100%'}}
            dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
            treeData={handleData(cateData)}
            placeholder="一级接口"
            treeDefaultExpandAll
            onChange={ () => {}}
            allowClear={true}
          />
        </Form.Item>

        <ProFormText
          name="api_name"
          label="接口名称"
          placeholder="请输入接口名称"
          rules={[
            {required: true, message: '接口名称不能为空'}
          ]}
        />
        <ProFormText
          name="api_url"
          label="接口链接"
          placeholder="请输入接口链接"
        />
        <ProFormText
          name="api_sort"
          label="排序"
          placeholder="请输入排序"
        />
      </ProForm>

    </Modal>
  );
};

export default Edit;
